<template>
  <div>
    <el-main>
      <el-row>
        <el-col :span="12" :xs="24">
          <div style="font-size: 24px; font-weight: bold; margin-bottom: 20px">
            添加需求
          </div>
          <el-form ref="form" :rules="rules" :model="form" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12" :xs="24">
                <el-form-item label="企业名称" prop="company">
                  <el-row style="">
                    <el-col :span="24">
                      <div style="display: flex">
                        <el-autocomplete
                          ref="selectRef"
                          clearable
                          style="width: 100%"
                          class="inline-input"
                          v-model="form.company"
                          :fetch-suggestions="querySearch"
                          placeholder="请输入公司名称"
                          :trigger-on-focus="false"
                          @select="handleSelect"
                        >
                          <template slot-scope="{ item }">
                            <div class="name">{{ item.company_name }}</div>
                          </template>
                        </el-autocomplete>
                        <div style="display: flex; align-items: center">
                          <el-button
                            :loading="buttonType"
                            size="mini"
                            style="margin-left: 10px; font-size: 14px; height: 38px"
                            type="primary"
                            plain
                            @click="handleSearchTYC"
                            >搜索</el-button
                          >
                        </div>
                      </div>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
              <el-col :span="24" :xs="24">
                <el-form-item :label="'企业需求'" prop="des">
                  <el-input
                    :autosize="{ minRows: 3, maxRows: 10 }"
                    type="textarea"
                    v-model="form.des"
                  >
                  </el-input>
                </el-form-item>
                <el-form-item label="解决人" prop="so_id">
                  <el-select
                    value-key="id"
                    v-model="form.so_id"
                    filterable
                    multiple
                    placeholder=""
                  >
                    <el-option
                      v-for="item in SolverList"
                      :key="item.id"
                      :label="item.username"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="需求标签">
                  <div>
                    <el-tag
                      v-for="(item_, index_) in Visitpeoplelist"
                      :key="item_.id"
                      class="b_bule b_red red_active"
                      >{{ item_.name }}</el-tag
                    >
                  </div>

                  <el-button
                    class="button_from_i"
                    type="primary"
                    round
                    @click="addType = !addType"
                  >
                    {{ addType ? "保存标签 —" : "添加标签 +" }}</el-button
                  >
                  <div v-if="addType">
                    <el-tag
                      @click="labelChange(item_, index_)"
                      :class="Visitpeoplelist.includes(item_) ? 'red_active' : ''"
                      v-for="(item_, index_) in labelList"
                      :key="item_.id"
                      class="b_bule b_red"
                      >{{ item_.name }}</el-tag
                    >
                  </div>
                </el-form-item>
                <el-form-item class="" label="期望解决时间" prop="solve_time">
                  <el-date-picker
                    type="datetime"
                    placeholder=""
                    v-model="form.solve_time"
                    format="yyyy-MM-dd HH:mm"
                    style="min-width: 27%"
                    value-format="yyyy-MM-dd HH:mm"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>

              <el-col :span="24" :xs="24" v-if='editType'>
                <el-form-item label="解决时间">
                  <el-date-picker
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm"
                    placeholder=""
                    format="yyyy-MM-dd HH:mm"
                    v-model="form.so_time"
                    style="min-width: 27%"
                  >
                  </el-date-picker>
                </el-form-item>

                <el-form-item label="解决方案">
                  <el-input
                    type="textarea"
                    v-model="form.solve_des"
                    :autosize="{ minRows: 3, maxRows: 10 }"
                  >
                  </el-input>
                </el-form-item>

                <el-form-item label="解决方案附件" class="upload_box">
                  <el-upload
                    :limit="1"
                    id="b_upload"
                    class="upload-demo"
                    :action="action"
                    :on-change="upload_success"
                    :on-remove="removeProgramme"
                    :file-list="form.fileList"
                    :before-upload="SolutionUpload"
                  >
                    <el-button
                      class="button_from_i"
                      slot="trigger"
                      size="small"
                      type="primary"
                      >解决方案 +</el-button
                    >
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="dialog-footer">
            <el-button type="primary" @click="preservation('form')">添加</el-button>
          </div>
        </el-col>
      </el-row>
    </el-main>
  </div>
</template>

<script>
import {
  seachCompany,
  labelTrue,
  staff,
  companyLabel,
  createVisit,
  pushUser,
  sendInfo,
  companyStreet,
  changeStreet,
  getBusinessCardInfo,
  deamdLabel,
  demandCreate,
  getCompany,
} from "@/api/newuser";
import { VUE_APP_BASE_API } from "@/config.js";

export default {
  data() {
    var checkSo_id = (rule, value, callback) => {
      if (!value.length) {
        return callback(new Error("解决人不能为空"));
      }
      callback();
    };

    var checkCompany = (rule, value, callback) => {
      if (!this.company_id) {
        return callback(new Error("请搜索并选择正确的公司"));
      }
      callback();
    };

    return {
      id: this.$store.state.user.id,
      choose: false,
      Visit: false,
      // action: `${VUE_APP_BASE_API}/v1/common/file`,
      action: `https://patent.shundeip.com/v1/common/file`,

      SeachType: false,
      dialogImageUrl: "",
      user_id: this.$store.state.user.id,
      dialogVisible: false,
      disabled: false,
      buttonType: false,
      Visitpeoplelist: [],
      VisitpeoplelistId: [],
      company_id: "",
      form: {
        company_id: "",
        des: "",
        label: [],
        so_id: [],
        company: "",
        solve_time: "",
        so_time:'',
        solve_des: '',
        fileList: []
      },
      StreetId: "",
      defaultLabel: [],
      company: "",
      seachCompanyList: [],
      labelList: [],
      SelectCompanyName: "",
      StreetList: [],
      fileList: [],
      hideUpload: "",

      SolverList: [],
      addType: false,
      rules: {
        company: [{ required: true, validator: checkCompany, trigger: "blur" }],
        des: [{ required: true, message: "请填写企业需求", trigger: "blur" }],
        so_id: [{ required: true, validator: checkSo_id, trigger: "blur" }],
        solve_time: [{ required: true, message: "请选择期望解决时间", trigger: "blur" }],
      },
      editType: false,
    };
  },
  watch: {
    addVisit() {
      this.Visit = this.addVisit;
      // console.log(this.addVisit)
    },
    add_form: {
      handler(newVal, oldVal) {
        this.form = newVal;
      },
      immediate: true,
      deep: true,
    },
  },
  props: {
    addVisit: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    add_form: {
      type: Object,
      default: () => {
        return {
          name: "",
          time: "",
          Visitpeople: "",
          enterprise: [],
        };
      },
    },
  },
  components: {},
  mounted() {
    this.staff();
    this.deamdLabel();

    if(this.$route.query.id){
      this.editType = true
    }
  },
  methods: {
    upload_success(file, fileList) {
      this.form.complete.fileList = fileList;
      let b_dom = document.getElementById("b_upload").getElementsByClassName("el-upload");
      b_dom[0].style.display = "none";
    },
    removeProgramme(file) {
      let b_dom = document.getElementById("b_upload").getElementsByClassName("el-upload");
      b_dom[0].style.display = "inline-block";
      this.form.complete.fileList = [];
    },
    SolutionUpload(file) {
      const isIMG = file.type.slice(0, 5) === "image";
      if (isIMG) {
        this.$message.error("请上传文件!");
      }
      return !isIMG;
    },
    labelChange(item, index) {
      if (this.Visitpeoplelist.includes(item)) {
        this.Visitpeoplelist.splice(this.Visitpeoplelist.indexOf(item), 1);
        this.VisitpeoplelistId.splice(this.VisitpeoplelistId.indexOf(item.id), 1);
      } else {
        this.Visitpeoplelist.push(item);
        this.VisitpeoplelistId.push(item.id);
      }
    },
    deamdLabel() {
      //需求标签获取
      deamdLabel().then((res) => {
        this.labelList = res;
      });
    },
    staff() {
      staff({
        id: this.user_id,
        type: 2,
      }).then((res) => {
        console.log(res, "res");
        this.SolverList = res;
      });
    },
    handleRemove(file) {
      this.hideUpload = false;
      console.log(file);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    handleSearchTYC() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (this.form.company == "") {
        this.$message({
          message: "请输入公司名称",
          type: "warning",
        });
        return;
      }
      this.buttonType = true;
      this.timer = setTimeout(() => {
        seachCompany({ keword: this.form.company }).then((res) => {
          this.buttonType = false;
          this.seachCompanyList = res.slice(0, 1000);
          var restaurants = this.seachCompanyList;
          this.$refs["selectRef"].$data.suggestions = restaurants;
          this.$refs.selectRef.focus();
        });
      }, 500);
    },
    querySearch(queryString, cb) {
      cb([]);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
      };
    },
    handleSelect(item) {
      console.log(item, "item 111", item.id);
      if (item.id) {
        this.company_id = item.id;
        this.form.company = item.company_name;
      } else {
        getCompany({
          company: item.company_name,
        }).then((res) => {
          this.company_id = res.id;
          this.form.company = item.company_name;
        });
      }
    },
    changeStreet(company) {
      if (!company) {
        this.StreetId = "";
        return;
      }
      changeStreet({ company: company }).then((res) => {
        this.StreetId = Number(res.street_id);
        console.log(this.StreetId, "this.form.StreetId");
      });
    },
    async companyStreet() {
      let data = await companyStreet();
      this.StreetList = data;
    },
    SelectCompany(item) {
      // console.log(item);
      this.form = {
        company_id: Number,
        time: "",
        Visitpeople: [],
        enterprise: [],
      };
      this.form.company_id = item;
      this.choose = false;
      if (item) {
        labelTrue({ id: item });
        companyLabel({ id: item }).then((res) => {
          // console.log(res);
          this.defaultLabel = res.result;
          this.labelList = res.list;
          this.labelList.map((res_) => {
            res.label.map((res_1) => {
              if (res_.id == res_1.id) {
                this.form.enterprise.push(res_);
              }
            });
          });
        });
      } else {
        this.defaultLabel = [];
        this.labelList = [];
      }
    },
    seachInputType() {
      this.SeachType = false;
    },
    //模糊查询
    seachCompany(query) {
      seachCompany({ keword: query }).then((res) => {
        this.seachCompanyList = res.slice(0, 1000);
      });
    },
    //关闭弹窗
    close() {
      this.$emit("close");
    },
    //保存
    preservation(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let form = {
            company_id: this.company_id,
            des: this.form.des,
            label: this.VisitpeoplelistId.join(","),
            solve_time: this.form.solve_time,
            so_id: this.form.so_id.join(","),
          };
          demandCreate(form).then((res) => {
            console.log(res, "adsasdasd");
            this.$router.push({
              path: "/workWaitvisit3?type=5",
            });
          });
        } else {
          this.$message.error("请完善需求表单信息");
          return false;
        }
      });
    },

    addEnterprise() {
      this.choose = !this.choose;
    },
    addLabel(item) {
      let index = this.form.enterprise.indexOf(item);
      if (index == -1) {
        this.form.enterprise.push(item);
      } else {
        this.form.enterprise.splice(index, 1);
      }
    },

    beforeAlbumUpload(file) {
      //上传前验证
      const isIMG = file.type.slice(0, 5) === "image";
      if (!isIMG) {
        this.$message.error("请上传图片!");
      }
      return isIMG;
    },
    onSuccess(response, file, fileList) {
      this.hideUpload = true;
      this.fileList = fileList;

      getBusinessCardInfo({
        file_path: response.data.url,
      }).then((res) => {
        console.log(res, "res");
        this.form_reception.email = res.email;
        this.form_reception.username = res.name;
        this.form_reception.address = res.address;
        this.form_reception.mobile = res.phone;
        this.form_reception.business_card = response.data.url;
        this.$message({
          message: "上传成功",
          type: "success",
        });
      });

      console.log(response, file, fileList, "上传成功");
    },
    handleChange(file, fileList) {
      this.fileList = fileList;

      console.log(this.fileList, 6666, file, fileList);
    },
  },
};
</script>

<style scoped lang="less">
::v-deep .el-upload-list__item {
  .el-loading-parent--relative {
    width: 100%;
    height: 100%;
  }
}

::v-deep .hide .el-upload--picture-card {
  display: none;
}

.el-main {
  margin: 20px 15px;
}

.b_bule {
  background-color: #d3e2ff;
  margin: 3px 5px;
  border-radius: 5px;
  color: #4585ff;
  font-size: 14px;
  height: 20px;
  line-height: 20px;
  border: 0;
  cursor: pointer;
}

.b_red {
  color: #ff5f58 !important;
  background-color: #fff6f5 !important;
}

.red_active {
  color: #fff6f5 !important;
  background-color: #ff5f58 !important;
}
.title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
}

::v-deep .upload-demo {
  .el-upload {
    // width: 100%;
    .upload {
      width: 500px;
      height: 300px;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}

::v-deep .el-upload--picture-card {
  width: 520px;
  height: 320px;
}
.seachCompanyList {
  position: absolute;
  top: 40px;
  background-color: #fff;
  z-index: 2;
  height: 200px;
  overflow: scroll;
  overflow-x: auto;
  border: 1px solid #f4f5f7;

  div {
    padding: 0 5px;
    cursor: pointer;
  }

  div:hover {
    background-color: #c1c1c1;
  }
}

.button_from_i {
  min-width: 161px;
  height: 38px;
  line-height: 0px;
  font-size: 14px;
  color: #3377ff;
  background-color: #ebf2ff;
  border: 1px solid #387dff;
  border-radius: 30px;
}

.dialog-footer {
  margin-top: 30px;
  button {
    padding: 5px 30px;
    width: 139px;
    height: 38px;
    background: #387dff;
    border: 1px solid #e8ecef;
    border-radius: 19px;
    font-size: 14px;
  }
}

.b_choose {
  display: inline-block;
  background-color: #ffffff;
  margin: 3px 5px;
  border-radius: 5px;
  padding: 0px 10px;
  color: #387dff;
  font-size: 12px;
  height: 22px;
  line-height: 20px;
  border: 1px solid #387dff;
  cursor: pointer;
}

::v-deep .el-table__row td:nth-child(6) .el-button {
  color: #23b899;
  background-color: #ecfaf7;
  border: none;
  font-size: 14px;
}

::v-deep input {
  border-radius: 38px;
  height: 38px;
  line-height: 38px;
}

::v-deep .el-input__icon {
  line-height: 38px;
  font-size: 16px;
}

.Visitdate {
  margin-top: 62px;
}

::v-deep .el-table__row td:nth-child(7) .el-button {
  color: #23b899;
  background-color: #ecfaf7;
  border: none;
}

::v-deep .el-dialog {
  border-radius: 10px;
}

::v-deep .el-dialog__header {
  .el-dialog__title {
    font-size: 22px;
    font-weight: bolder;
  }

  .el-dialog__headerbtn {
    i {
      position: absolute;
      border: 3px solid #fff;
      top: -50px;
      left: 30px;
      color: #fff;
      border-radius: 30px;
      font-size: 24px;
      font-weight: bolder;
    }
  }
}

::v-deep .el-form-item {
  .el-form-item__label {
    font-size: 14px;
    font-weight: initial;
  }

  .el-form-item__content {
    .el-input__inner {
      border-radius: 5px;
    }
  }
}

@media (max-width: 768px) {
  .el-main {
    margin: 0;
    height: 100vh;
  }

  .Visitdate {
    margin-top: 0;
  }

  .el-form-item__content {
    .el-select {
      width: 100%;
    }
  }

  ::v-deep .el-popper {
    left: 22px !important;
  }
}

@media (max-width: 1280px) {
}

@media (max-width: 1360px) {
}
</style>
